package cn.tk.resource.loader;

import org.springframework.core.io.ClassPathResource;
import cn.tk.exception.CustomException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by denglw on 2019/6/10.<br/>
 * Desc: 类路径下资源加载器
 */
public final class ResLoader {

    /**
     * 加载类文件，获取文件输入流.<br/>
     * @param classPath 类路径
     * @return io流
     */
    public static InputStream load(String classPath) {
        if (classPath == null || classPath.trim().length() == 0) {
            throw new CustomException("类文件路径不能为空");
        }
        // 包含有classpath前缀的, 清除前缀
        if (classPath.startsWith("classpath:")) {
            classPath = classPath.replaceFirst("classpath:", "").trim();
        }
        ClassPathResource resource = new ClassPathResource(classPath);
        try {
            return resource.getInputStream();
        } catch (IOException e) {
            throw new CustomException("获取类路径文件流失败: " + e.getMessage());
        }
    }

    /**
     * 使用utf8解析文件，获取文件行列表.<br/>
     * @param classPath 类文件路径
     * @return list
     */
    public static List<String> readLines(String classPath) {
        // 默认utf-8编码
        return readLines(classPath, StandardCharsets.UTF_8);
    }

    /**
     * 按照指定编码获取文件行列表.<br/>
     * @param classPath 类文件路径
     * @param charset 编码
     * @return list
     */
    public static List<String> readLines(String classPath, Charset charset) {
        InputStream inputStream = load(classPath);
        return readLines(inputStream, charset);
    }

    /**
     * 获取文件行列表.<br/>
     * @param is 输入流
     * @return list
     */
    public static List<String> readLines(InputStream is) {
        return readLines(is, StandardCharsets.UTF_8);
    }

    /**
     * 按照指定编码获取文件行列表.<br/>
     * @param is 输入流
     * @param charset 编码
     * @return list
     */
    public static List<String> readLines(InputStream is, Charset charset) {
        InputStreamReader streamReader = new InputStreamReader(is, charset);
        BufferedReader reader = new BufferedReader(streamReader);
        try {
            return reader.lines().collect(Collectors.toList());
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }

}
